package com.masterclient.app.modules.search;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.managerlibrary.router.AroutePath;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.income.model.EcItemDataBean;
import com.masterclient.app.modules.search.beans.SearchResultDataBean;
import com.masterclient.app.modules.search.contract.SearchResultContract;
import com.masterclient.app.modules.search.contract.SearchResultPresenter;
import com.masterclient.app.utils.CommonUtil;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

import static com.eoner.common.config.Config.SEARCH_HISTORY;

/**
 * 作者：sean
 * 创建时间：2017/8/4 13:17
 * 功能说明：
 */
@Route(path = AroutePath.SEARCH_RESULT_FRAGMENT)
public class SearchResultFragment extends BaseFragment<SearchResultPresenter> implements SearchResultContract.View {
    @BindView(R.id.et_search_text)
    EditText etSearchText;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.view_no_data)
    View viewNoData;

    List<SearchResultDataBean.ProductItem> list;
    private boolean hasMore;
    private int page = 1;

    Gson gson = new Gson();
    private List<String> historyQueue;
    private String history;
    private SearchResultAdapter recycleAdapter;

    @Autowired(name = "keyword")
    String keyword;

    public static SearchResultFragment getInstance() {
        return new SearchResultFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_search_result, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        ARouter.getInstance().inject(this);

        history = SPUtils.getInstance().getString(SEARCH_HISTORY);
        historyQueue = gson.fromJson(history, new TypeToken<ArrayList<String>>() {
        }.getType());
        etSearchText.setText(keyword);

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recycleAdapter = new SearchResultAdapter();
        recycleAdapter.setOnItemClickListener((adapter, view, position) -> {
            SearchResultDataBean.ProductItem item = list.get(position);
            CommonUtil.goAnyWhere(mContext,item.productUrl,"","","","","");
        });
        recyclerView.setAdapter(recycleAdapter);
        recycleAdapter.bindToRecyclerView(recyclerView);

        recycleAdapter.setOnLoadMoreListener(() -> {
            if (hasMore) {
                page++;
                mPresenter.getSearchResult(String.valueOf(page), PAGE_SIZE, keyword);
            }
        }, recyclerView);

        swipeLayout.setOnRefreshListener(() -> {
            if (list != null) {
                list.clear();
                recycleAdapter.notifyDataSetChanged();
            }
            recycleAdapter.setEnableLoadMore(true);
            page = 1;
            mPresenter.getSearchResult(String.valueOf(page), PAGE_SIZE, keyword);
        });

        page = 1;
        mPresenter.getSearchResult(String.valueOf(page), PAGE_SIZE, keyword);
    }

    @OnClick({R.id.tv_search, R.id.view_back})
    void back(View v) {
        switch (v.getId()) {
            case R.id.tv_search:
                // 当按了搜索之后关闭软键盘
                String search = etSearchText.getText().toString().trim();
                hideSoftInput(etSearchText);
                if (TextUtils.isEmpty(search)) {
                    showToast("搜索内容不能为空");
                } else {
                    searchKeywords(search);
                }
                break;
            case R.id.view_back:
                getActivity().finish();
                break;
        }
    }

    private void searchKeywords(String search) {
        if (historyQueue == null) {
            historyQueue = new ArrayList<>();
            historyQueue.add(search);
            SPUtils.getInstance().put(SEARCH_HISTORY, gson.toJson(historyQueue));
        } else {
            if (historyQueue.contains(search)) {
                historyQueue.remove(search);
                historyQueue.add(search);
                SPUtils.getInstance().put(SEARCH_HISTORY, gson.toJson(historyQueue));
            } else {
                historyQueue.add(search);
                SPUtils.getInstance().put(SEARCH_HISTORY, gson.toJson(historyQueue));
            }
        }

        page = 1;
        keyword = search;
        mPresenter.getSearchResult(String.valueOf(page), PAGE_SIZE, keyword);
    }

    @Override
    public void getSearchResultSuccess(SearchResultDataBean dataBean) {
        if (swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }

        this.page = Integer.parseInt(dataBean.page);
        if (list == null) {
            list = new ArrayList<>();
        }

        if (page == 1) {
            list.clear();
            page++;
            mPresenter.getSearchResult(String.valueOf(page), PAGE_SIZE, keyword);
        }
        if (page == 1 && (dataBean.products == null || dataBean.products.size() == 0)) {
            swipeLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            viewNoData.setVisibility(View.VISIBLE);
        } else {
            if(page == 2 && list.size() == 0 && (dataBean.products == null || dataBean.products.size() == 0)){
                swipeLayout.setVisibility(View.GONE);
                recyclerView.setVisibility(View.GONE);
                viewNoData.setVisibility(View.VISIBLE);
            }else {
                swipeLayout.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.VISIBLE);
                viewNoData.setVisibility(View.GONE);
                list.addAll(dataBean.products);
                recycleAdapter.setNewData(list);
                recycleAdapter.setEnableLoadMore(true);
                hasMore = true;
                if (page > 1 && (dataBean.products == null || dataBean.products.size() == 0)) {
                    hasMore = false;
                    recycleAdapter.setEnableLoadMore(false);
                }
                recycleAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void getSearchResultFailed(String msg) {
        if (swipeLayout != null) {
            swipeLayout.setRefreshing(false);
        }
    }
}
